package com.pine.dcts.config;

import com.alibaba.datax.common.constant.PluginType;
import com.pine.dcts.common.DctsException;
import com.pine.dcts.service.JobService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.HashMap;
import java.util.Map;

import static com.pine.dcts.utils.FileUtils.getAbsPath;


/**
 *  核心配置加载类
 */
@EnableTransactionManagement
@Configuration
@Slf4j
@Order(20)
public class DctsConfig implements ApplicationRunner {
    private static final String pluginTypeNameFormat = "plugin.%s.%s";
    /**
     *  datax的核心配置
     */
    public static  com.alibaba.datax.common.util.Configuration CONFIGURATION;

    @Autowired
    private DctsPropertis corePropertis;

    @Autowired
    private JobService jobService;

    /**
     *  job配置中心
     */
    public static final Map<String, com.alibaba.datax.common.util.Configuration> jobConfigCenter = new HashMap<>();
    public void parserConfiguration(){
        if(this.corePropertis==null|| StringUtils.isEmpty(corePropertis.getPath())){
           throw new DctsException("datax的核心配置文件不能为空");
        }
        String path = getAbsPath(corePropertis.getPath());
        log.info("datax核心配置文件路径为：{}",path);
        com.alibaba.datax.common.util.Configuration configuration = null;
            configuration = DctsConfigParser.parseCoreConfig( path);
        CONFIGURATION = configuration;
        log.info("datax核心配置文件解析完成");
    }

    public void loadJobConfig(){
        if(this.corePropertis==null||corePropertis.getJobs().size()==0){
            throw new DctsException("datax的核心配置文件不能为空");
        }
        for(String key : corePropertis.getJobs().keySet()){
            String value = corePropertis.getJobs().get(key);
            String path = getAbsPath(value);
            String json = DctsConfigParser.getJobContent(path);
          com.alibaba.datax.common.util.Configuration configuration =  DctsConfigParser.parse(json);
            jobConfigCenter.put(key,configuration);
        }
    }




    @Override
    public void run(ApplicationArguments args) throws Exception {
        /**
         *  解析核心配置文件
         */
        parserConfiguration();
        /**
         *  加载所有job配置信息
         */
        loadJobConfig();
    }

    private static String generatePluginKey(PluginType pluginType,
                                            String pluginName) {
        return String.format(pluginTypeNameFormat, pluginType.toString(),
                pluginName);
    }

}
